package com.greedy.service;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.greedy.bean.pojo.VoucherOrder;
import com.greedy.interceptor.UserHolder;
import com.greedy.utils.RedisIdWorker;
import com.greedy.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.n3r.eql.Eql;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.greedy.constants.CommentConstants.SECKILL_ORDER_STOCK_KEY;


/**
 * @Author: Yanxy
 * @Date: Created in:2022-12-28
 * Description:
 */
@Slf4j
@Service
public class VoucherOrderService {

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 定义LUA脚本
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    /**
     * 创建线程池（阿里巴巴手册命令禁止，我这是为了省事）
     */
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    // 初始化LUA脚本
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 下单队列要优于抢单任务之前
     */
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    // ================================================ 业务开始 ================================================

    /**
     * 获取消息队列中的消息进行处理
     */
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 获取队列里的订单
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    // 判断订单信息
                    if (CollectionUtils.isEmpty(list)) {
                        continue;
                    }
                    // 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 创建订单
                    createVoucherOrder(voucherOrder);
                    // 手动ACK
                    stringRedisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    handlePendingList();
                }
            }
        }
    }

    /**
     * 下订单异常补偿机制
     */
    private void handlePendingList() {
        while (true) {
            try {
                // 1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),
                        StreamReadOptions.empty().count(1),
                        StreamOffset.create("stream.orders", ReadOffset.from("0"))
                );
                // 2.判断订单信息是否为空
                if (list == null || list.isEmpty()) {
                    // 如果为null，说明没有异常消息，结束循环
                    break;
                }
                // 解析数据
                MapRecord<String, Object, Object> record = list.get(0);
                Map<Object, Object> value = record.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                // 3.创建订单
                createVoucherOrder(voucherOrder);
                // 4.确认消息 XACK
                stringRedisTemplate.opsForStream().acknowledge("s1", "g1", record.getId());
            } catch (Exception e) {
                log.error("处理订单异常", e);
            }
        }
    }

    /**
     * 生成订单
     *
     * @param voucherOrder 订单实体
     */
    private void createVoucherOrder(VoucherOrder voucherOrder) {
        Eql eql = new Eql();
        HashMap<String, Object> eqlParams = new HashMap<>();
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        Long id = voucherOrder.getId();
        // 创建锁对象
        RLock redisLock = redissonClient.getLock(SECKILL_ORDER_STOCK_KEY + userId);
        // 获取锁失败，直接返回失败或者重试
        if (!redisLock.tryLock()) {
            log.error("不允许重复下单！");
            return;
        }
        try {
            // 查询订单
            eqlParams.put("userId", userId);
            eqlParams.put("voucherId", voucherId);
            String orderIsExist = eql.selectFirst("orderIsExist").params(eqlParams).returnType(String.class).execute();
            // 用户已经购买过了
            if (StringUtils.isNotBlank(orderIsExist)) {
                log.error("不允许重复下单！");
                return;
            }
            // 扣减库存
            int deductStock = eql.update("deductStock").params(voucherId).returnType(Integer.class).execute();
            // 扣减失败
            if (deductStock == 0) {
                log.error("库存不足！");
                return;
            }
            // 创建订单落库
            eqlParams.put("id", id);
            eql.insert("saveOrder").params(eqlParams).execute();
            log.info("优惠券订单创建完成-优惠券信息：{}", JSON.toJSONString(eqlParams));
        } finally {
            // 释放锁
            redisLock.unlock();
        }
    }

    /**
     * 秒杀优惠券
     *
     * @param voucherId 优惠券ID
     * @return 用户拥有购买资格，返回订单ID。否侧返回其它标识 1:库存不足;2:该用户已经下过单
     */
    public Result seckillVoucher(Long voucherId) {
        // 获取用户ID
        Long userId = UserHolder.getUser().getId();
        // 生成订单ID
        long orderId = redisIdWorker.nextId("order");
        // 执行LUA脚本
        Long executeResult = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                String.valueOf(voucherId),
                String.valueOf(userId),
                String.valueOf(orderId)
        );
        // 返回标识为：1 或 2
        int r = 0;
        if (executeResult != null) {
            r = executeResult.intValue();
        }
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 返回订单ID
        return Result.ok(orderId);
    }


}
